﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MinistryStandardPlatformEntity;
using MinistryStandardPlatformWeb;
using Webdiyer.WebControls.Mvc;

namespace MinistryStandardPlatformWeb.Controllers
{
    [IsLogin]
    public class StaffController : Controller
    {
        //
        // GET: /Staff/
        private MSPDataContext context = new MSPDataContext();

        [MenuAuthorized("17")]
        public ActionResult Index()
        {
            var staffs = from s in context.InfoStaff
                         orderby s.InsertTime descending
                         select s;

            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                string id = HttpUtility.UrlDecode(Request.QueryString["id"]);
                staffs = from s in staffs
                         where s.ParentUnitId == id
                         orderby s.InsertTime descending
                         select s;

            }
            return PartialView(staffs.ToPagedList(1, CommonDictionary.PageSize));
        }

        [MenuAuthorized("174")]
        public ActionResult Data(string condition, string unitId, string searchAll, int pageIndex = 1)
        {
            var staffs = from s in context.InfoStaff
                            orderby s.InsertTime descending
                            select s;
            if (!string.IsNullOrEmpty(unitId) && searchAll != "on")
            {
                staffs = from s in staffs
                            where s.ParentUnitId == unitId
                         orderby s.InsertTime descending
                            select s;

            }
            if (!string.IsNullOrEmpty(unitId) && searchAll == "on")
            {
                List<string> ids = CommonFunctions.GetAllChildrenUnits(unitId, CommonFunctions.GetLoginUser().UserId);
                ids.Add(unitId);
                staffs = from r in staffs
                            where ids.Contains(r.ParentUnitId)
                            orderby r.ParentUnitId, r.InsertTime descending
                            select r;
            }
            if (!string.IsNullOrEmpty(condition))
            {
                staffs = from s in staffs
                            where s.StaffName.Contains(condition)
                            orderby s.InsertTime descending
                            select s;

            }
            return PartialView(staffs.ToPagedList(pageIndex, CommonDictionary.PageSize));
        }


        [MenuAuthorized("171")]
        public ActionResult Create()
        {
            string unitId = HttpUtility.UrlDecode(Request.QueryString["unitId"]);
            string unitName = HttpUtility.UrlDecode(Request.QueryString["unitName"]);

            ViewBag.StaffType = context.Dictionary_Detail.Where(d => d.TypeID == "zd004").AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text=d.DicName,
                    Value=d.DicID
                }).ToList();

            return View(new InfoStaff()
            {
                ParentUnitId = unitId,
                InfoUnit = new InfoUnit()
                {
                    UNITID = unitId,
                    UNITNAME = unitName
                }
            });
        }

        //选择所属单位
        public ActionResult PickParentUnit()
        {
            var units = context.RightsDetails.Where(u => u.UserId == CommonFunctions.GetLoginUser().UserId && u.NodeTYPE == true).Select(u => new { NodeId = u.NodeId, ParentNodeId = u.ParentNodeId, NodeName = u.NodeName });
            List<ZTreeNode> nodes = new List<ZTreeNode>();
            foreach (var unit in units)
            {
                ZTreeNode node = new ZTreeNode();
                node.id = unit.NodeId;
                node.pId = unit.ParentNodeId;
                node.name = unit.NodeName;
                node.icon = "/Content/themes/zTreeStyle/img/diy/1_open.png";
                if (unit.ParentNodeId == null)
                {
                    node.open = true;
                }
                else
                {
                    node.open = false;
                }
                nodes.Add(node);
            }
            ViewBag.nodesJson = CommonFunctions.ListToJsonStr<ZTreeNode>(nodes);
            return View();
        }

        [HttpPost]
        [MenuAuthorized("171")]
        public ActionResult Create(InfoStaff staff)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    staff.StaffId = "STAF" + CommonFunctions.GetDateTimeStrAnd4BitsRandom();
                    staff.InsertTime = DateTime.Now;
                    staff.InsertUserId = CommonFunctions.GetLoginUser().UserId;
                    context.InfoStaff.InsertOnSubmit(staff);
                    context.SubmitChanges();
                    ViewBag.Message = "添加成功";

                    List<SelectListItem> items = new List<SelectListItem>();
                    items.Add(new SelectListItem());

                    ViewBag.StaffType = new SelectList(items);
                }
                catch (System.Exception ex)
                {
                    ViewBag.Message = "添加失败," + ex.Message;
                    ViewBag.StaffType = context.Dictionary_Detail.Where(d => d.TypeID == "zd004").AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.DicName,
                        Value = d.DicID
                    }).ToList();
                }
            }
            else
            {
                ViewBag.Message = "添加失败";
                ViewBag.StaffType = context.Dictionary_Detail.Where(d => d.TypeID == "zd004").AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text = d.DicName,
                    Value = d.DicID
                }).ToList();
            }
            return View(staff);
        }

        [MenuAuthorized("172")]
        public ActionResult Delete(string parameters)
        {
            var staff = context.InfoStaff.SingleOrDefault(s => s.StaffId == parameters);

            try
            {
                context.InfoStaff.DeleteOnSubmit(staff);
                context.SubmitChanges();
                return Json(new { success = true, message = "" });
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        [MenuAuthorized("173")]
        public ActionResult Edit(string id)
        {
            var staff = context.InfoStaff.SingleOrDefault(s => s.StaffId == id);
            ViewBag.StaffType = context.Dictionary_Detail.Where(d => d.TypeID == "zd004").AsEnumerable()
               .Select(d => new SelectListItem
               {
                   Text = d.DicName,
                   Value = d.DicID,
                   Selected=d.DicID==staff.StaffType
               }).ToList();
            return View(staff);
        }

        [HttpPost]
        [MenuAuthorized("173")]
        public ActionResult Edit(FormCollection form)
        {
            try
            {
                var staffToUpdate = context.InfoStaff.SingleOrDefault(s => s.StaffId == form["StaffId"]);
                UpdateModel(staffToUpdate, form.ToValueProvider());
                context.SubmitChanges();
                ViewBag.Message = "修改成功";

                List<SelectListItem> items = new List<SelectListItem>();
                items.Add(new SelectListItem());

                ViewBag.StaffType = new SelectList(items);
                return View(staffToUpdate);
            }

            catch (System.Exception ex)
            {
                ViewBag.Message = "修改失败," + ex.Message;
                ViewBag.StaffType = context.Dictionary_Detail.Where(d => d.TypeID == "zd004").AsEnumerable()
               .Select(d => new SelectListItem
               {
                   Text = d.DicName,
                   Value = d.DicID
               }).ToList();

                return View(new InfoTower());
            }

        }

    }
}
